import { verify } from './verify.js';
import { request } from './request.js';

var _request = new request();

var options = {
    sex: null,
};
var formatOptions = function (value, type) {
    if (type == 'list') {
        var data = [];
        for (var i = 0; i < value.length; i++) {
            var item = value[i];
            data.push(item);
        };
    } else if (type == 'data') {
        var data = {};
        for (var i = 0; i < value.length; i++) {
            var item = value[i];
            data[item.value] = item;
        };
    };
    return data;
};

var getByAjax = function (name, callBack) {
    _request.GET({
        url: '/optionSide/' + name,
        success: function (result) {
            callBack(result);
        }
    });
};

var recursionOptions = function (nameArray, callback, type) {
    if (type == 'data') {
        var resultData = {};
    } else {
        type = 'list';
        var resultData = [];
    };
    var name = nameArray.shift();
    getByAjax(name, function (result) {
        options[name] = {};
        options[name].list = formatOptions(result, 'list');
        options[name].data = formatOptions(result, 'data');
        callback($.extend(true, resultData, options[name][type]), nameArray, name);
    })
};

var getOptions = function (name, callback, type) {
    if (verify.is('string', name)) {
        if (type == 'data') {
            var resultData = {};
        } else {
            type = 'list';
            var resultData = [];
        };
        if (options[name] !== null) {
            callback($.extend(true, resultData, options[name][type]));
        } else {
            getByAjax(name, function (result) {
                options[name] = {};
                options[name].list = formatOptions(result, 'list');
                options[name].data = formatOptions(result, 'data');
                callback($.extend(true, resultData, options[name][type]));
            })
        };
    } else if (verify.is('array', name)) {
        var data = {};
        var _name = $.extend(true, [], name);

        function loop() {
            recursionOptions(_name, function (result, array, nameItem) {
                data[nameItem] = result;
                if (array.length == 0) {
                    callback(data);
                } else {
                    loop();
                };
            }, type);
        };
        loop();
    };
};

export const optionSide = {
    get: getOptions,
    setEvent: function (event) {
        getByAjax = event;
    },
    setFormat: function (event) {
        formatOptions = event
    }
};